package com.bj58.ecdata.util;

import com.google.common.base.Joiner;

/**
 * @author lichao
 * @date 2014年11月27日
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {
	private static final Joiner joinerWithBlank = Joiner.on(" ").skipNulls();
	private static final Joiner joinerWithUnderline = Joiner.on("_").skipNulls();

	public static String joinWithBlank(Object first, Object second, Object... rest) {
		return joinerWithBlank.join(first, second, rest);
	}

	public static String joinWithUnderline(Object first, Object second, Object... rest) {
		return joinerWithUnderline.join(first, second, rest);
	}

	public static String[] trimSplit(String str, String separatorChars) {
		return split(trimToNull(str), separatorChars);
	}

	/**
	 * @param template
	 *            %s
	 * @param args
	 * @return
	 */
	public static String format(String template, Object... args) {
		template = String.valueOf(template); // null -> "null"

		// start substituting the arguments into the '%s' placeholders
		StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
		int templateStart = 0;
		int i = 0;
		while (i < args.length) {
			int placeholderStart = template.indexOf("%s", templateStart);
			if (placeholderStart == -1) {
				break;
			}
			builder.append(template.substring(templateStart, placeholderStart));
			builder.append(args[i++]);
			templateStart = placeholderStart + 2;
		}
		builder.append(template.substring(templateStart));

		// if we run out of placeholders, append the extra args in square braces
		if (i < args.length) {
			builder.append(" [");
			builder.append(args[i++]);
			while (i < args.length) {
				builder.append(", ");
				builder.append(args[i++]);
			}
			builder.append(']');
		}

		return builder.toString();
	}

}
